package com.hzit.sb2.controller;

import com.hzit.sb2.bean.weixinEntity.BaseMsg;
import com.hzit.sb2.service.IAutoCallBackService;
import com.hzit.sb2.util.SecurityKit;
import com.thoughtworks.xstream.XStream;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;

@Controller
public class BaseController {

    @Autowired
    IAutoCallBackService autoCallBackService;

    /**
     * 自定义随机数
     */
    String token = "lucas_token";

    @RequestMapping(value = "/init", method = RequestMethod.GET)
    @ResponseBody
    public String init(String signature, String timestamp, String nonce, String echostr){
        String[] strArr = {token,timestamp,nonce};
        //按字典排序
        Arrays.sort(strArr);
        String str = "";
//        拼接字符串
        for (String s : strArr) {
            str += s;
        }
        System.out.println("字符串："+str);
        //sha1加密
        String sha1 = SecurityKit.sha1(str);
        if(sha1.equals(signature)){
            return echostr;
        }
        return null;
    }

    @RequestMapping(value = "/init",method = RequestMethod.POST)
    @ResponseBody
    public String msg(HttpServletRequest request) throws IOException, DocumentException {
        ServletInputStream is = request.getInputStream();
        SAXReader reader = new SAXReader();
        Document document = reader.read(is);
        String sendMsg = autoCallBackService.autoCallBackMsg(document);
        return sendMsg;
    }
}
